﻿using HPIT.Shop.Common;
using HPIT.Shop.DTO;
using HPIT.Shop.IServices;
using HPIT.Shop.Services.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace HPIT.Shop.Services
{
    public class Loginservice : ILoginservice
    {
        //#region 判断手机号和密码是否正确
        public bool CheckUser(LoginDTO dto)
        {
            using (var db = new ShopContext())
            {
                //查找数据库
                BaseService<Logn> bs = new BaseService<Logn>(db);
                //根据手机号进行查找用户信息进行登录
                var model = bs.Get(e => e.MobileNumber == dto.MobileNumber);
                var SaltPassword = model.saltPassword;
                if (model != null)
                {
                    //如果查询到了进行下一步验证
                    //判断密码是否正确
                    //是否和加密后的密码一样
                    if (CommonHelper.CalcMD5(dto.Password+SaltPassword) != model.Password)
                    {
                        return false;
                    }
                    else
                    {
                        SetUserData(model);
                        return true;
                    }
                }
                return false;
            };
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public AjaxResult register(registerDTO dto)
        {
            using (var db = new ShopContext())
            {
                //查找数据库
                BaseService<Logn> bs = new BaseService<Logn>(db);
                //调用工具类生成盐
                var SaltPassword =  CommonHelper.CreateVerifyCode(4);
                var dtoPassword = CommonHelper.CalcMD5(dto.Password+ SaltPassword);
                var model = new Logn()
                {
                    MobileNumber = dto.MobileNumber,
                    Password = dtoPassword,
                    UserName = dto.UserName,
                    saltPassword= SaltPassword,
            };
                //写入到客户端Cookie中（利用Forms身份验证机制）
                SetUserData(model);
                if (bs.Add(model) > 0)
                    return new AjaxResult(ResultState.Success, "注册成功");
                else
                    return new AjaxResult(ResultState.Error, "注册失败");
            }
        }
        private void SetUserData(Logn loginDTO)
        {
            //1.将用户信息对象转化成json格式（序列化）
            //封装一个扩展方法，方便json格式序列化
            var userData = loginDTO.Tojson();

            //2.创建加密票据
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, "loginUser", DateTime.Now, DateTime.Now.AddDays(1), false, userData);

            //3.对票据进行加密
            string tickeEncrypt = FormsAuthentication.Encrypt(ticket);

            //4.讲加密之后的用户信息写入到Cookie中
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, tickeEncrypt);
            cookie.Path = FormsAuthentication.FormsCookiePath;

            //当用户勾选了记住我，则需要指定cookie有效期（无勾选默认一天）
            //if (IsRemeberMe)
            //{
            //    cookie.Expires = DateTime.Now.AddHours(6);
            //}
            cookie.Expires = DateTime.Now.AddHours(24);
            //5.讲Cookie写入响应流中发给客户端

            //获取http请求上上下文
            HttpContext context = HttpContext.Current;
            //最好先将原来的移除掉
            context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            context.Response.Cookies.Add(cookie);
        }
    }
}
